package com.winning.vsts.merge.service.service;

import com.alibaba.fastjson.JSONObject;
import com.winning.vsts.merge.service.configuration.VstsContext;
import com.winning.vsts.merge.service.domain.PullRequest;
import com.winning.vsts.merge.service.domain.VstsProject;
import com.winning.vsts.merge.service.entity.PullRequestDO;
import com.winning.vsts.merge.service.jpa.PullRequestJpaRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 记录pull request 请求
 *
 * @author xcl <xcl@winning.com.cn>
 * @date 2021/11/18
 */
@Service
public class RecordPullRequestService {

    private static final Logger logger = LoggerFactory.getLogger(RecordPullRequestService.class);

    @Autowired
    private PullRequestJpaRepository pullRequestJpaRepository;

    @Autowired
    private List<PullRequestService> pullRequestServices;

    @Autowired
    private VstsContext vstsContext;

    @Autowired
    private VstsProjectService vstsProjectService;

    @Autowired
    private VstsClient vstsClient;


    @Transactional(rollbackFor = Exception.class)
    public PullRequest savePullRequest(PullRequestDO pullRequestDO) {
        return pullRequestJpaRepository.save(PullRequest.createPullRequest(pullRequestDO));
    }

    @Transactional(rollbackFor = Exception.class)
    public void updatePullRequestStatus(Integer requestId, JSONObject jsonObject) {
        PullRequest pullRequest = PullRequest.createPullRequest(requestId, jsonObject);
        pullRequestJpaRepository.updatePullRequestStatus(requestId, pullRequest.getVstsId(), pullRequest.getStatus(),
            pullRequest.getMergeStatus(), pullRequest.getUpdateTime(), pullRequest.getRequestUrl());
    }


    public void createPullRequest(VstsProject vstsProject, String sourceBranch, String targetBranch, String pullNo) {
        RestTemplate restTemplate = vstsContext.restTemplate(vstsProject);
        PullRequestService pullRequestService = this.pullRequestServices.stream()
            .filter(item -> item.isSupport(targetBranch))
            .findAny()
            .orElseThrow(() -> new RuntimeException("没有对应的分支" + targetBranch + "处理"));
        pullRequestService.pullRequest(restTemplate, vstsProject, sourceBranch, targetBranch, pullNo);
    }


    public List<PullRequest> queryNotCompleted() {
        return pullRequestJpaRepository.queryNotCompleted();
    }


    public void queryPullRequestStatus() throws Exception {
        logger.info("===============================自动查询开启===============================");
        for (int i = 0; i < 10; i++) {
            List<PullRequest> pullRequests = queryNotCompleted();
            if (CollectionUtils.isEmpty(pullRequests)) {
                break;
            }
            for (PullRequest pullRequest : pullRequests) {
                Integer projectId = pullRequest.getProjectId();
                VstsProject vstsProject = vstsProjectService.getVstsProject(projectId);
                RestTemplate restTemplate = vstsContext.restTemplate(vstsProject);
                String pullRequestId = pullRequest.getVstsId();
                JSONObject jsonObject = vstsClient.queryPullRequest(restTemplate, vstsProject, pullRequestId);
                updatePullRequestStatus(pullRequest.getId(), jsonObject);
            }

            TimeUnit.SECONDS.sleep(30);
        }
        logger.info("===============================自动查询关闭===============================");
    }

    public void printActivePullRequest() {
        logger.info("===============================需要审批的链接===============================");
        List<PullRequest> pullRequests = pullRequestJpaRepository.queryActive();
        for (int i = 0; i < pullRequests.size(); i++) {
            PullRequest pullRequest = pullRequests.get(i);
            System.out.println(pullRequest.getRequestUrl());
            System.out.println();
            if (i != 0 && i % 5 == 0) {
                System.out.println();
            }
        }
        logger.info("===============================需要审批的链接===============================");
    }


    public void queryActiveRequestStatus() throws Exception {
        logger.info("===============================自动查询激活的PR开启===============================");
        for (int i = 0; i < 10; i++) {
            List<PullRequest> pullRequests = pullRequestJpaRepository.queryActive();
            if (CollectionUtils.isEmpty(pullRequests)) {
                break;
            }
            for (PullRequest pullRequest : pullRequests) {
                Integer projectId = pullRequest.getProjectId();
                VstsProject vstsProject = vstsProjectService.getVstsProject(projectId);
                RestTemplate restTemplate = vstsContext.restTemplate(vstsProject);
                String pullRequestId = pullRequest.getVstsId();
                JSONObject jsonObject = vstsClient.queryPullRequest(restTemplate, vstsProject, pullRequestId);
                updatePullRequestStatus(pullRequest.getId(), jsonObject);
            }

            TimeUnit.SECONDS.sleep(30);
        }
        logger.info("===============================自动查询激活的PR关闭===============================");
    }
}
